package com.njcb.ams.web.controller.system;

import com.njcb.ams.application.BusinessSystemWebManager;
import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.pojo.dto.UserModfiyPwdDTO;
import com.njcb.ams.pojo.dto.standard.EntityResponse;
import com.njcb.ams.pojo.dto.standard.PageResponse;
import com.njcb.ams.pojo.dto.standard.Response;
import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.repository.dao.CommUserInfoDAO;
import com.njcb.ams.repository.entity.CommUserInfo;
import com.njcb.ams.service.BusinessAuthorityService;
import com.njcb.ams.store.page.Page;
import com.njcb.ams.store.page.PageHandle;
import com.njcb.ams.support.exception.ExceptionUtil;
import com.njcb.ams.support.security.bo.SecurityUser;
import com.njcb.ams.util.AmsAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * 用户操作类
 *
 * @author LOONG
 */
@RestController
@RequestMapping("/system/userinfo")
@Api(value = "userinfo", tags = "userinfo")
public class UserSetController {

    @Autowired
    private BusinessSystemWebManager businessManager;
    @Autowired
    private CommUserInfoDAO userInfoDAO;
    @Autowired
    private BusinessAuthorityService authorityService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "获取用户列表", notes = "根据任意条件查询用户列表")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    @ResponseBody
    public PageResponse<CommUserInfo> queryUser(@RequestBody CommUserInfo userInfo) throws Exception {
        userInfo.setOrgIdList(authorityService.selectSelfAndSubById());
        PageHandle.startPage(userInfo);
        List<CommUserInfo> list = businessManager.queryUser(userInfo);
        Page page = PageHandle.endPage();
        return PageResponse.build(list, page.getTotal());
    }

    @ApiOperation(value = "新增用户信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public Response saveUserInfo(@RequestBody CommUserInfo userInfo) throws Exception {
        businessManager.saveUserInfo(userInfo);
        return Response.buildSucc();
    }

    @ApiOperation(value = "删除用户信息")
    @RequestMapping(value = "{loginName}/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Response removeUserInfo(@ApiParam(required = true, value = "用户名") @PathVariable("loginName") String loginName) throws Exception {
        CommUserInfo userInfo = userInfoDAO.findByLoginName(loginName);
        businessManager.removeUserInfo(userInfo);
        return Response.buildSucc();
    }

    @ApiOperation(value = "修改用户密码", notes = "根据用户名修改密码")
    @RequestMapping(value = "{loginName}/modfiyPwd", method = RequestMethod.POST)
    @ResponseBody
    public Response modfiyPwd(@ApiParam(required = true, value = "用户名") @PathVariable("loginName") String loginName,
                              @ApiParam(required = true, value = "旧密码") @RequestParam String oldPassword,
                              @ApiParam(required = true, value = "新密码") @RequestParam String newPassword) throws Exception {
        AmsAssert.notNull(loginName, "用户名不能为空");
        AmsAssert.notNull(oldPassword, "旧密码不能为空");
        AmsAssert.notNull(newPassword, "新密码输入错误");

        CommUserInfo userInfo = userInfoDAO.findSecurityUserByLoginName(loginName);
        AmsAssert.notNull(userInfo, "用户名[" + loginName + "]不存在");

        if (!passwordEncoder.matches(oldPassword, userInfo.getPassWord())) {
            ExceptionUtil.throwAppException("旧密码输入错误");
        }

        int row = businessManager.resetPwd(loginName, newPassword);

        if (row > 0) {
            return Response.buildSucc();
        } else {
            return Response.buildFail("密码修改错误");
        }

    }

    @ApiOperation(value = "修改用户密码", notes = "根据用户名修改密码")
    @RequestMapping(value = "modfiyPwd", method = RequestMethod.POST)
    @ResponseBody
    public Response modfiyPwdJson(@RequestBody UserModfiyPwdDTO userModfiyPwdDTO) throws Exception {
        AmsAssert.notNull(userModfiyPwdDTO.getLoginName(), "用户名不能为空");
        AmsAssert.notNull(userModfiyPwdDTO.getOldPassword(), "旧密码不能为空");
        AmsAssert.notNull(userModfiyPwdDTO.getNewPassword(), "新密码输入错误");
        CommUserInfo userInfo = userInfoDAO.findSecurityUserByLoginName(userModfiyPwdDTO.getLoginName());
        AmsAssert.notNull(userInfo, "用户名[" + userModfiyPwdDTO.getLoginName() + "]不存在");
        if (!passwordEncoder.matches(userModfiyPwdDTO.getOldPassword(), userInfo.getPassWord())) {
            ExceptionUtil.throwAppException("旧密码输入错误");
        }
        int row = businessManager.resetPwd(userModfiyPwdDTO.getLoginName(), userModfiyPwdDTO.getNewPassword());
        if (row > 0) {
            return Response.buildSucc();
        } else {
            return Response.buildFail("密码修改错误");
        }
    }


    @ApiOperation(value = "重置用户密码")
    @RequestMapping(value = "{loginName}/reset", method = RequestMethod.POST)
    @ResponseBody
    public Response resetPwd(@ApiParam(required = true, value = "用户登陆名") @PathVariable("loginName") String loginName) throws Exception {
        int row = businessManager.resetPwd(loginName, SysBaseDefine.DEFAULT_PASSWORD);
        businessManager.unlockUser(loginName);
        if (row > 0) {
            return Response.buildSucc();
        } else {
            return Response.buildFail("密码重置错误");
        }
    }

    @ApiOperation(value = "解锁用户")
    @RequestMapping(value = "{loginName}/unlock", method = RequestMethod.POST)
    @ResponseBody
    public Response unlockUser(@ApiParam(required = true, value = "用户名") @PathVariable("loginName") String loginName) throws Exception {
        businessManager.unlockUser(loginName);
        return Response.buildSucc();
    }

    @ApiOperation(value = "剔除用户")
    @RequestMapping(value = "{loginName}/kickOut", method = RequestMethod.POST)
    @ResponseBody
    public Response kickOutOnlineUser(@ApiParam(required = true, value = "用户名") @PathVariable("loginName") String loginName) throws Exception {
        businessManager.kickOutOnlineUser(loginName);
        return Response.buildSucc();
    }

    @ApiOperation(value = "清除用户会话")
    @RequestMapping(value = "{loginName}/clear", method = RequestMethod.POST)
    @ResponseBody
    public Response clearUserSession(@ApiParam(required = true, value = "用户名") @PathVariable("loginName") String loginName) throws Exception {
        businessManager.clearUserSession(loginName);
        return Response.buildSucc();
    }

    @ApiOperation(value = "获取当前用户")
    @RequestMapping(value = "/current", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public EntityResponse<SecurityUser> getInfo() throws Exception {
        return getSecurityUserEntityResponse();
    }

    static EntityResponse<SecurityUser> getSecurityUserEntityResponse() {
        SecurityUser loginUser = new SecurityUser();
        loginUser.setSysName(StringUtils.isEmpty(SysBaseDefine.SYS_NAME) ? "管理系统" : SysBaseDefine.SYS_NAME);
        loginUser.setBusiDate(DataBus.getBusiDate());
        loginUser.setId(DataBus.getUserId());
        loginUser.setLoginName(DataBus.getLoginName());
        loginUser.setUserName(DataBus.getUserName());
        loginUser.setOrgnName(DataBus.getOrgName());
        loginUser.setRoleCodes(DataBus.getRoleCodes());
        return EntityResponse.build(loginUser);
    }

    @ApiOperation(value = "获取当前用户")
    @RequestMapping(value = "/admininfo", method = RequestMethod.GET)
    @ResponseBody
    @RolesAllowed("ADMIN")
//	@PreAuthorize("hasRole('ROLE_ADMIN')")
    public EntityResponse<SecurityUser> getAdminInfo() throws Exception {
        return getSecurityUserEntityResponse();
    }

}
